package servlet;

import dao.UserDao;
import model.User;
import utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/4/8 14:31
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    public UserDao userDao = new UserDao();
    /**
     * 判断用户是否登录, 如果登录, 返回用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取登录的用户信息
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("user") == null){ //此处get的是一个Object对象
            resp.getWriter().write(JSONUtils.toJSON(new User()));
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null || user.getId()<=0){ //此处，可能强转完事null （其他类型的对象）
            resp.getWriter().write(JSONUtils.toJSON(new User()));
            return;
        }
        System.out.println(user.getId() );
        resp.getWriter().write(JSONUtils.toJSON(user));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        System.out.println(name);
        System.out.println(password);
        if (name==null || "".equals(name)|| password==null || "".equals(password) ){
            //todo 以弹窗的形式出现
            resp.getWriter().write("账号或者密码不能为空");
            return;
        }
        User user = userDao.selectByName(name);

        if (user==null || user.getId()<=0){

            resp.getWriter().write("用户不存在或者账号不合法");
            return;
        }
        if (!password.equals(user.getPasswd())){
            resp.getWriter().write("密码错误");
            return;
        }
        HttpSession session = req.getSession(true);
        user.setPasswd("");
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }
}
